//
//  LaunchVC.swift
//  mmda
//
//  Created by 李陆涛 on 2018/4/16.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import CoreTelephony

class LaunchVC: BaseVC {
    
    
    @IBOutlet weak var logoTop: NSLayoutConstraint!
    var viewModel: LaunchViewModel!
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setup()
        self.motionNetworkStatus()
    }
    
    func setup() {
        
        self.logoTop.constant = CGFloat(kScreenHeight - 80 - 30)
        self.viewModel = LaunchViewModel()
        
        self.viewModel.loadSuccess = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.logoTop.constant = CGFloat(kNavigationBarHeight)
            
            UIView.animate(withDuration: 1, animations: {
                
                self.view.layoutIfNeeded()
            }, completion: { suc in
                
                let baseVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "BaseNav")
                
                self.view.window?.rootViewController = baseVC
                
                
            })
        }
        
        viewModel.loadFaild = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            let alertVC = UIAlertController(title: nil, message: errmsg, preferredStyle: UIAlertControllerStyle.alert)
            
            alertVC.addAction(UIAlertAction(title: "重试", style: UIAlertActionStyle.default, handler: { _ in
                
                self.viewModel.start()
            }))
            
            alertVC.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: nil))
            
            self.present(alertVC, animated: true, completion: nil)
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        
        return true
    }
    
    private func motionNetworkStatus() {
        
        let cellular = CTCellularData()
        
        self.handCellular(status: cellular.restrictedState)
        
        cellular.cellularDataRestrictionDidUpdateNotifier = {
            
            [weak self] status in
            guard let `self` = self else { return }
            
            self.handCellular(status: status)
        }
    }
    
    private func handCellular(status:CTCellularDataRestrictedState) {
        
        
        switch status {
            
        case .restrictedStateUnknown,.notRestricted:
            
            self.viewModel.start()
        case .restricted:
            
            self.showToast("网络请求已关闭，无法获取内容")
        }
    }
}




